// pages/rentedbook/rentedbook.js
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {

    arr: [],
    brr: [],
    crr: [],

    bookid: null,
    booktitle: null,
    bookauthor: null,
    bookcountry: null,
    bookpublisher: null,
    bookdetail: null,
    bookdate: null,
    bookisbn: null,
    hosterid: null,
    hostername: null,
    bookimage: null,
    bookowner: null,
    bookownerid: null,
    bookrentrecord: null,
    bookrentdate: null,
    bookrenew: null,


    hosterid: null,

    rentday: null,
    renewday: 7,
    rentnum: null,
    nearbyday: 7

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    //1.获取token
    wx.request({
      url: "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential",
      data: {
        appid: getApp().globalData.appID,
        secret: getApp().globalData.appSecret
      },
      success: function (res) {
        console.log('access_token:', res.data.access_token)
        getApp().globalData.access_token = res.data.access_token;
      }
    })

    this.setData(
      {
        hosterid: options.hosterid,
      }
    )

    /* 初始化数据库 */
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('RentPara')
      .where
      ({
        rtype: _.eq('图书')
      })
      .get
      ({
        success: res => {
          this.setData(
            {
              rentday: res.data[0].rentDay,
              rentnum: res.data[0].rentNum,
            }
          )
          db.collection('Books').where
            ({
              ownerid: _.eq(this.data.hosterid)
            })
            .get
            ({
              success: res => {
                this.setData({
                  arr: res.data
                });

                var brr = this.data.arr
                var blength = this.data.arr.length
                // console.log('666', blength)
                for (var i = 0; i < blength; i++) {
                  var length = this.data.arr[i].ownerid.length
                  // console.log('666', length)
                  for (var j = 0; j < length; j++) {
                    if (this.data.arr[i].ownerid[j] == this.data.hosterid) {
                      var rentflag = 0
                      brr[i].renew = this.data.arr[i].renew[j]
                      brr[i].ownerid = this.data.arr[i].ownerid[j]
                      brr[i].owner = this.data.arr[i].owner[j]
                      var renewday = this.data.renewday
                      var thisbookrenew = brr[i].renew
                      console.log('thisbookrenew', brr[i].renew)
                      if (thisbookrenew == true) {
                        rentflag = 1
                        console.log('rentflag', rentflag)
                      }

                      var n_to = this.data.arr[i].rentdate[j] * 1000
                      var rent_date = new Date(n_to);
                      console.log('N-To:', n_to)
                      console.log('rent_date', rent_date)
                      brr[i].rentdate = util.formatTime(rent_date)

                      var w_temp = this.data.rentday
                      console.log('w_temp', w_temp)
                      var m_to = n_to + 24 * 60 * 60 * 1000 * this.data.rentday + 24 * 60 * 60 * 1000 * rentflag * this.data.renewday
                      var return_date = new Date(m_to);
                      console.log('M-To:', m_to)
                      console.log('return_date', return_date)
                      brr[i].returndate = util.formatTime(return_date)

                      var timestamp = Date.parse(new Date());
                      var i_to = (m_to - timestamp) / (24 * 60 * 60 * 1000)
                      brr[i].restday = parseInt(i_to)
                      console.log('restday', i_to)

                    }
                  }
                }



                this.setData({
                  brr: brr
                })

                console.log('数据库查询成功:', res.data)

              },
              fail: err => {
                wx.showToast({
                  icon: 'none',
                  title: '查询记录失败'
                })
                console.error('数据库查询失败', err)
              }
            })


        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })




  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {


  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },


  //续借按钮
  renew: function (event) {
    var that = this

    console.log(event)
    this.setData
      ({

        bookid: event.currentTarget.dataset.rentid

      })
    /* 初始化数据库 */
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('Books').where
      ({
        _id: _.eq(this.data.bookid)
      })
      .get
      ({
        success: res => {
          this.setData({
            booktitle: res.data[0].title,
            bookauthor: res.data[0].author,
            bookpublisher: res.data[0].publisher,
            bookowner: res.data[0].owner,
            bookdata: util.formatTime(res.data[0].pubdate),
            bookdetail: res.data[0].summary,
            bookimage: res.data[0].image,
            bookrenew: res.data[0].renew,
            bookownerid: res.data[0].ownerid,
            bookrentrecord: res.data[0].rentrecord,
            bookrentdate: res.data[0].rentdate,
          });
          console.log('1 flag')
          var bookowneridtem = this.data.bookownerid
          var bookrenewtem = this.data.bookrenew
          var length = this.data.bookownerid.length

          for (var j = 0; j < length; j++) {
            if (bookowneridtem[j] == this.data.hosterid) {

              bookrenewtem[j] = true

              break
            }
          }
          console.log('2 flag')
          this.setData
            ({
              bookrenew: bookrenewtem
            })
          wx.cloud.callFunction
            ({
              // 云函数名称
              name: 'renew',
              // 传给云函数的参数
              data:
              {
                bookid: this.data.bookid,
                bookrenew: this.data.bookrenew,
              },

              success: function (res) {
                console.log(res)
                var HosterID = that.data.hosterid
                wx.redirectTo({                                   
                  url: '../rentedbook/rentedbook?hosterid=' + HosterID,
                })
              },

              fail: console.error
            })

          wx.showToast({
            title: '续借成功',
            icon: 'error',
            duration: 2000          //提示的延迟时间
          })

        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })

  },

})